import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { Form, Select, Spin, Typography, Tabs, InputNumber, Row, Col, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { getAnimationList } from '@/services/project';
import { useSelector, useDispatch } from 'react-redux';
import { selectTextAnimationById, updateTextProperties } from '@/store/textsSlice';
import type { RootState } from '@/store';

const { Title, Text } = Typography;
const { Option } = Select;

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* ... (样式代码与之前组件相同，此处为简洁省略) ... */
    .config-text-animation-scroll::-webkit-scrollbar { width: 3px; background: transparent; }
    .config-text-animation-scroll::-webkit-scrollbar-thumb { background: #715BB8; border-radius: 4px; }
    .ant-form-item-label > label { color: #FFFFFF !important; }
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important; color: #FFFFFF !important; border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus, .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important; box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
    .ant-tabs-nav { margin-bottom: 24px !important; }
    .ant-tabs-tab { color: #AAAAAA !important; }
    .ant-tabs-tab:hover { color: #FFFFFF !important; }
    .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn { color: #715BB8 !important; }
    .ant-tabs-ink-bar { background: #715BB8 !important; }
`;

interface ConfigTextAnimationFormProps {
    textId: string;
}

const animationTypeMap = {
    intro_animations: 'Text_intro',
    outro_animations: 'Text_outro',
    loop_animations: 'Text_loop_anim',
};

const animationTypeNameMap: Record<string, string> = {
    Text_intro: '入场',
    Text_outro: '出场',
    Text_loop_anim: '循环',
};

const tabItems = [
    { key: 'intro_animations', label: '入场动画' },
    { key: 'outro_animations', label: '出场动画' },
    { key: 'loop_animations', label: '循环动画' },
];

const ConfigTextAnimationForm: React.FC<ConfigTextAnimationFormProps> = ({ textId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    const textAnimations = useSelector((state: RootState) => (textId ? selectTextAnimationById(state, textId) : []));
    const [animationsData, setAnimationsData] = useState<any>({});
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('intro_animations');

    const currentAnimation = useMemo(() => {
        if (!textId) return null;
        const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
        const animations = Array.isArray(textAnimations) ? textAnimations : [];
        return animations.find((anim) => anim.animation_type === type) || null;
    }, [textAnimations, activeTab, textId]);

    useEffect(() => {
        setLoading(true);
        getAnimationList()
            .then((res) => setAnimationsData(res.data?.data || {}))
            .catch((error) => console.error('获取文本动画列表失败:', error))
            .finally(() => setLoading(false));
    }, []);

    useEffect(() => {
        if (currentAnimation) {
            form.setFieldsValue({
                animation_params: currentAnimation.params,
                duration: parseFloat(currentAnimation.duration) || 1,
            });
        } else {
            form.resetFields(['animation_params', 'duration']);
        }
    }, [currentAnimation, form]);

    // 处理动画下拉框选择，单独获取下拉框值并更新到Redux
    const handleAnimationSelect = useCallback(
        (animationName: string | null) => {
            if (!textId) return;

            const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
            const currentAnimations = Array.isArray(textAnimations) ? [...textAnimations] : [];
            let updatedAnimations;

            // 获取表单中的持续时间值
            const duration = form.getFieldValue('duration') || 1;

            if (!animationName) {
                // 如果清除了选择，则移除该类型的动画
                updatedAnimations = currentAnimations.filter((anim) => anim.animation_type !== type);
            } else {
                // 找到该类型动画在数组中的位置
                const animationIndex = currentAnimations.findIndex((anim) => anim.animation_type === type);
                const newAnimationData = {
                    animation_type: type,
                    params: animationName,
                    duration: `${duration}s`,
                };

                if (animationIndex !== -1) {
                    // 更新已存在的动画
                    currentAnimations[animationIndex] = {
                        ...currentAnimations[animationIndex],
                        ...newAnimationData,
                    };
                    updatedAnimations = currentAnimations;
                } else {
                    // 添加新动画
                    updatedAnimations = [...currentAnimations, newAnimationData];
                }
            }

            // 更新Redux状态
            dispatch(
                updateTextProperties({
                    id: textId,
                    updates: { animation: updatedAnimations },
                })
            );
        },
        [textId, activeTab, textAnimations, dispatch, form]
    );

    // 处理持续时间变化
    const handleDurationChange = useCallback(
        (duration: number) => {
            if (!textId || !form.getFieldValue('animation_params')) return;

            const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
            const currentAnimations = Array.isArray(textAnimations) ? [...textAnimations] : [];
            const animationIndex = currentAnimations.findIndex((anim) => anim.animation_type === type);

            if (animationIndex !== -1) {
                currentAnimations[animationIndex] = {
                    ...currentAnimations[animationIndex],
                    duration: `${duration}s`,
                };

                dispatch(
                    updateTextProperties({
                        id: textId,
                        updates: { animation: currentAnimations },
                    })
                );
            }
        },
        [textId, activeTab, textAnimations, dispatch, form]
    );

    // 处理整体表单变化（保持向后兼容）
    const handleFormChange = useCallback(
        (changedValues: any, allValues: any) => {
            if (!textId) return;

            // 如果是动画效果变化
            if ('animation_params' in changedValues) {
                handleAnimationSelect(allValues.animation_params);
            }
            // 如果是持续时间变化
            else if ('duration' in changedValues && allValues.animation_params) {
                handleDurationChange(allValues.duration);
            }
        },
        [textId, handleAnimationSelect, handleDurationChange]
    );

    const animationsForCurrentTab: any[] = animationsData[activeTab] || [];

    if (!textId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何文本片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-text-animation-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前动画
                </Title>
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>{currentAnimation ? `${animationTypeNameMap[currentAnimation.animation_type]}: ${currentAnimation.params} (${currentAnimation.duration})` : '无动画'}</Text>
                </div>

                <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />

                <Form form={form} layout="vertical" onValuesChange={handleFormChange} initialValues={{ duration: 1.0 }}>
                    <Row gutter={16} align="bottom">
                        <Col span={16}>
                            <Form.Item label="动画效果" name="animation_params">
                                <Spin spinning={loading}>
                                    <Select
                                        placeholder="请选择或清除动画"
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) => String(option?.children).toLowerCase().includes(input.toLowerCase())}
                                        onSelect={handleAnimationSelect}
                                        onClear={() => handleAnimationSelect(null)}
                                    >
                                        {animationsForCurrentTab.map((anim) => (
                                            <Option key={anim.name} value={anim.name}>
                                                {anim.display_name}
                                                {anim.is_vip ? ' (VIP)' : ''}
                                            </Option>
                                        ))}
                                    </Select>
                                </Spin>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="持续时间" name="duration">
                                <InputNumber min={0.1} max={10} step={0.1} style={{ width: '90%' }} addonAfter="s" onChange={() => handleDurationChange} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </>
    );
};

export default ConfigTextAnimationForm;
